const Router = require('koa-router')
const files = new Router()
const db = require('../mysql/index');
const koaBody = require("koa-body");
var fs = require('fs')
const path = require('path')
const compressing = require('compressing');


files.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200*1024*1024*1024    // 设置上传文件大小最大限制，默认2M
    }
}))

const dealFile = (file,url) => {
    const reader = fs.createReadStream(file.path);
    const writer = fs.createWriteStream(
        path.resolve(__dirname, url, file.name)
    );

    return new Promise((resove, reject) => {

        reader.pipe(writer);

        reader.on('end', () => {
            resove(true);
        });

        reader.on('error', err => {
            throw err;
        })

    });
};

function unzip(filePath, distPath) {
    compressing.zip.uncompress(filePath, distPath).then(() => {}).catch(() => {});
}



//获取uuid文件名称（去掉扩展名）
function getFileName(data) {
    return data.substring(0,data.indexOf("."));
}

async function uploadfile(file,filePath){
    const reader = fs.createReadStream(file.path);
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    await reader.pipe(upStream);
}


files.post('/upload',(ctx) => {
    const file = ctx.request.files.file; // 获取上传文件
    const info = ctx.request.body
    let filePath = path.join(__dirname, '../static/gameres') + `/${file.name}`;
    let distPath = path.join(__dirname, '../static/game') + `/${getFileName(file.name)}`;
    let now = (new Date()).Format("yyyyMMdd")
    let dbPath = 'game' + `/${getFileName(file.name)}`+ '/index.html';
    const sql =`INSERT INTO game (G_NAME,G_DESC,G_TIME,G_URL,G_MAKER,G_MAKERID) VALUES ('${info.gamename}','${info.gamedesc}',${now},'${dbPath}','${info.username}','${info.userid}');`
    console.log(sql)
    ctx.body = '文件上传成功'
    db.query(sql,[],(res,err)=>{
        console.log(res,err)
    })
    dealFile(file,'../static/gameres').then(r => {
        unzip(filePath, distPath)
    })
});



files.post('/gamecover',(ctx) => {
    const file = ctx.request.files.file; // 获取上传文件
    const info = ctx.request.body
    let dbPath = 'img' + `/${file.name}`;
    ctx.body = '文件上传成功'
    const sql =`UPDATE game SET G_COVER = '${dbPath}' WHERE G_ID = ${info.G_ID}`
    console.log(sql)
    db.query(sql,[],(res,err)=>{
        console.log(res,err)
    })
    dealFile(file,'../static/img').then(r => {
        ctx.body = '文件上传成功'
    })
});

files.post('/header',(ctx) => {
    const file = ctx.request.files.file; // 获取上传文件
    const info = ctx.request.body
    let dbPath = 'header' + `/${file.name}`;
    ctx.body = '修改成功'

    if (file.name){
        console.log(file)
        dealFile(file,'../static/header').then(r => {
            ctx.body = '文件上传成功'
        })
        const sql =`UPDATE users SET USER_HEADER = '${dbPath}' WHERE USER_ID = ${info.userid}`
        console.log(sql)
        db.query(sql,[],(res,err)=>{
        })
    }
    if (info.username){
        const sql =`UPDATE users SET USER_NAME = '${info.username}' WHERE USER_ID = ${info.userid}`
        console.log(sql)
        db.query(sql,[],(res,err)=>{
        })
    }
    if (info.desc){
        const sql =`UPDATE users SET USER_DESC = '${info.desc}' WHERE USER_ID = ${info.userid}`
        db.query(sql,[],(res,err)=>{
        })
    }
    // const sql =`UPDATE users SET USER_DESC = '${info.desc}',user_header = '${info.dbPath}'  WHERE USER_ID = ${info.userid}`
    // console.log(sql)
    // db.query(sql,[],(res,err)=>{
    //     console.log(res,err)
    // })

});



module.exports = files
